package com.example.chatinterface;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.text.SimpleDateFormat;
import java.util.List;

public class MsgRecyclerViewAdapter extends RecyclerView.Adapter<MsgRecyclerViewAdapter.MyViewHolder> {

    enum ViewType {
        VIEW_TYPE_LEFT_MSG,
        VIEW_TYPE_RIGHT_MSG
    }

    private List<Msg> msgs;

    public MsgRecyclerViewAdapter(List<Msg> msgs) {
        this.msgs = msgs;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == ViewType.VIEW_TYPE_RIGHT_MSG.ordinal()) {
            return new MyViewHolder(LayoutInflater
                    .from(parent.getContext())
                    .inflate(R.layout.msg_item_right, parent, false));
        }
        return new MyViewHolder(LayoutInflater
                .from(parent.getContext())
                .inflate(R.layout.msg_item_left, parent, false));
    }

    @Override
    public int getItemViewType(int position) {
        if (msgs.get(position).getFromYou()) {
            return ViewType.VIEW_TYPE_RIGHT_MSG.ordinal();
        }
        return ViewType.VIEW_TYPE_LEFT_MSG.ordinal();
    }

    @Override
    public int getItemCount() {
        return msgs.size();
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        Msg msg = msgs.get(position);
        holder.text.setText(msg.getMsg());
        if (msg.getShowTime()) {
            holder.time.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(msg.getTime()));
        } else {
            holder.time.setVisibility(View.GONE);
        }
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        private TextView time;

        private ImageView avatar;

        private TextView text;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            time = itemView.findViewById(R.id.textView_time);
            avatar = itemView.findViewById(R.id.imageView_avatar);
            text = itemView.findViewById(R.id.textView_text);
        }
    }
}
